#include "MessageDispatcher.h"
#include "Entity/EntityManager.h"
#include "Time/TimerWin32.h"



MessageDispatcher* MessageDispatcher::Instance() {
	static MessageDispatcher instance;
	return &instance;
}



void MessageDispatcher::dischargeMessage(BaseEntity* p_receiver, const Telegram& p_message) {
	p_receiver->handleMessage(p_message);
}



void MessageDispatcher::dispatchMessage(double p_delay,
										int p_sender,
										int p_receiver,
										int p_message,
										void* p_extraInfo) {
	BaseEntity* ent_receiver = EntityManager::Instance()->getEntityFromID(p_receiver);
	
	Telegram telegram(p_delay, p_sender, p_receiver, p_message, p_extraInfo);

	if(p_delay <= 0.0) {
		dischargeMessage(ent_receiver, telegram);
	}
	else {
		telegram.dispatchTime = Timer::getTimeInRegister();
		telegram.dispatchTime += p_delay;

		m_messageQueue.insert(telegram);
	}
}



void MessageDispatcher::dispatchDelayedMessages() {
	double currentTime = Timer::getTimeInRegister();
	
	// dispatch messages that should be dispatched now
	while(	!(m_messageQueue.empty()) 
		&& m_messageQueue.begin()->dispatchTime < currentTime
        && m_messageQueue.begin()->dispatchTime > 0) {
		
		BaseEntity* ent_receiver = EntityManager::Instance()->getEntityFromID(m_messageQueue.begin()->receiver);
		dischargeMessage(ent_receiver, *m_messageQueue.begin());

		m_messageQueue.erase(m_messageQueue.begin());
	}
}